home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / sqlite / main.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  26.0 KB  |  569 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. from __future__ import nested_scopes
  5. import _sqlite
  6. import copy
  7. import new
  8. import sys
  9. import weakref
  10. from types import *
  11.  
  12. try:
  13.     from mx import DateTime
  14.     have_datetime = 1
  15. except ImportError:
  16.     have_datetime = 0
  17.  
  18. if have_datetime:
  19.     Date = DateTime.Date
  20.     Time = DateTime.Time
  21.     Timestamp = DateTime.Timestamp
  22.     DateFromTicks = DateTime.DateFromTicks
  23.     TimeFromTicks = DateTime.TimeFromTicks
  24.     TimestampFromTicks = DateTime.TimestampFromTicks
  25.     DateTimeType = DateTime.DateTimeType
  26.     DateTimeDeltaType = DateTime.DateTimeDeltaType
  27.  
  28.  
  29. class DBAPITypeObject:
  30.     
  31.     def __init__(self, *values):
  32.         self.values = values
  33.  
  34.     
  35.     def __cmp__(self, other):
  36.         if other in self.values:
  37.             return 0
  38.         
  39.         if other < self.values:
  40.             return 1
  41.         else:
  42.             return -1
  43.  
  44.  
  45.  
  46. def _quote(value):
  47.     """_quote(value) -> string
  48.  
  49.     This function transforms the Python value into a string suitable to send to
  50.     the SQLite database in a SQL statement.  This function is automatically
  51.     applied to all parameters sent with an execute() call.  Because of this a
  52.     SQL statement string in an execute() call should only use '%s' [or
  53.     '%(name)s'] for variable substitution without any quoting."""
  54.     if value is None:
  55.         return 'NULL'
  56.     elif type(value) in (IntType, LongType, FloatType):
  57.         return value
  58.     elif isinstance(value, StringType):
  59.         return "'%s'" % value.replace("'", "''")
  60.     elif hasattr(value, '__quote__'):
  61.         return value.__quote__()
  62.     elif hasattr(value, '_quote'):
  63.         return value._quote()
  64.     elif have_datetime and type(value) in (DateTime.DateTimeType, DateTime.DateTimeDeltaType):
  65.         return "'%s'" % value
  66.     else:
  67.         return repr(value)
  68.  
  69.  
  70. def _quoteall(vdict):
  71.     '''_quoteall(vdict)->dict
  72.     Quotes all elements in a list or dictionary to make them suitable for
  73.     insertion in a SQL statement.'''
  74.     if type(vdict) is DictType or isinstance(vdict, PgResultSet):
  75.         t = { }
  76.         for k, v in vdict.items():
  77.             t[k] = _quote(v)
  78.         
  79.     elif isinstance(vdict, StringType) or isinstance(vdict, UnicodeType):
  80.         t = (_quote(vdict),)
  81.     elif type(vdict) in (ListType, TupleType):
  82.         t = tuple(map(_quote, vdict))
  83.     else:
  84.         raise TypeError, 'argument to _quoteall must be a sequence or dictionary!'
  85.     return t
  86.  
  87.  
  88. class PgResultSet:
  89.     '''A DB-API query result set for a single row.
  90.     This class emulates a sequence with the added feature of being able to
  91.     reference a column as attribute or with dictionary access in addition to a
  92.     zero-based numeric index.'''
  93.     
  94.     def __init__(self, value):
  95.         self.__dict__['baseObj'] = value
  96.  
  97.     
  98.     def __getattr__(self, key):
  99.         key = key.upper()
  100.         if self._xlatkey.has_key(key):
  101.             return self.baseObj[self._xlatkey[key]]
  102.         
  103.         raise AttributeError, key
  104.  
  105.     
  106.     def __len__(self):
  107.         return len(self.baseObj)
  108.  
  109.     
  110.     def __getitem__(self, key):
  111.         if isinstance(key, StringType):
  112.             key = self.__class__._xlatkey[key.upper()]
  113.         
  114.         return self.baseObj[key]
  115.  
  116.     
  117.     def __contains__(self, key):
  118.         return self.has_key(key)
  119.  
  120.     
  121.     def __getslice__(self, i, j):
  122.         klass = make_PgResultSetClass(self._desc_[i:j])
  123.         obj = klass(self.baseObj[i:j])
  124.         return obj
  125.  
  126.     
  127.     def __repr__(self):
  128.         return repr(self.baseObj)
  129.  
  130.     
  131.     def __str__(self):
  132.         return str(self.baseObj)
  133.  
  134.     
  135.     def __cmp__(self, other):
  136.         return cmp(self.baseObj, other)
  137.  
  138.     
  139.     def description(self):
  140.         return self._desc_
  141.  
  142.     
  143.     def keys(self):
  144.         _k = []
  145.         for _i in self._desc_:
  146.             _k.append(_i[0])
  147.         
  148.         return _k
  149.  
  150.     
  151.     def values(self):
  152.         return self.baseObj[:]
  153.  
  154.     
  155.     def items(self):
  156.         _items = []
  157.         for i in range(len(self.baseObj)):
  158.             _items.append((self._desc_[i][0], self.baseObj[i]))
  159.         
  160.         return _items
  161.  
  162.     
  163.     def has_key(self, key):
  164.         return self._xlatkey.has_key(key.upper())
  165.  
  166.     
  167.     def get(self, key, defaultval = None):
  168.         if self.has_key(key):
  169.             return self[key]
  170.         else:
  171.             return defaultval
  172.  
  173.  
  174.  
  175. def make_PgResultSetClass(description):
  176.     NewClass = new.classobj('PgResultSetConcreteClass', (PgResultSet,), { })
  177.     NewClass.__dict__['_desc_'] = description
  178.     NewClass.__dict__['_xlatkey'] = { }
  179.     for _i in range(len(description)):
  180.         NewClass.__dict__['_xlatkey'][description[_i][0].upper()] = _i
  181.     
  182.     return NewClass
  183.  
  184.  
  185. class Cursor:
  186.     '''Abstract cursor class implementing what all cursor classes have in
  187.     common.'''
  188.     
  189.     def __init__(self, conn, rowclass = PgResultSet):
  190.         self.arraysize = 1
  191.         self.con = weakref.proxy(conn)
  192.         self.con.cursors[id(self)] = self
  193.         self.rowclass = rowclass
  194.         self._reset()
  195.         self.current_recnum = -1
  196.  
  197.     
  198.     def _reset(self):
  199.         self.closed = None
  200.         self.rowcount = -1
  201.         self._real_rowcount = 0
  202.         self.description = None
  203.         self.rs = None
  204.         self.current_recnum = 0
  205.  
  206.     
  207.     def _checkNotClosed(self, methodname = None):
  208.         if self.closed:
  209.             if not methodname:
  210.                 pass
  211.             raise _sqlite.ProgrammingError, '%s failed - the cursor is closed.' % ''
  212.         
  213.  
  214.     
  215.     def _unicodeConvert(self, obj):
  216.         """Encode all unicode strings that can be found in obj into
  217.         byte-strings using the encoding specified in the connection's
  218.         constructor, available here as self.con.encoding."""
  219.         if isinstance(obj, StringType):
  220.             return obj
  221.         elif isinstance(obj, UnicodeType):
  222.             return obj.encode(*self.con.encoding)
  223.         elif isinstance(obj, ListType) or isinstance(obj, TupleType):
  224.             converted_obj = []
  225.             for item in obj:
  226.                 if type(item) is UnicodeType:
  227.                     converted_obj.append(item.encode(*self.con.encoding))
  228.                     continue
  229.                 converted_obj.append(item)
  230.             
  231.             return converted_obj
  232.         elif isinstance(obj, DictType):
  233.             converted_obj = { }
  234.             for k, v in obj.items():
  235.                 if type(v) is UnicodeType:
  236.                     converted_obj[k] = v.encode(*self.con.encoding)
  237.                     continue
  238.                 converted_obj[k] = v
  239.             
  240.             return converted_obj
  241.         elif isinstance(obj, PgResultSet):
  242.             obj = copy.copy(obj)
  243.             for k, v in obj.items():
  244.                 if type(v) is UnicodeType:
  245.                     obj[k] = v.encode(*self.con.encoding)
  246.                     continue
  247.             
  248.             return obj
  249.         else:
  250.             return obj
  251.  
  252.     
  253.     def execute(self, SQL, *parms):
  254.         self._checkNotClosed('execute')
  255.         if self.con.autocommit:
  256.             pass
  257.         elif not self.con.inTransaction:
  258.             pass
  259.         if not (SQL[:6].upper() == 'SELECT'):
  260.             self.con._begin()
  261.             self.con.inTransaction = 1
  262.         
  263.         SQL = self._unicodeConvert(SQL)
  264.         if len(parms) == 0:
  265.             self.rs = self.con.db.execute(SQL)
  266.         elif len(parms) == 1 and type(parms[0]) in (DictType, ListType, TupleType) or isinstance(parms[0], PgResultSet):
  267.             parms = (self._unicodeConvert(parms[0]),)
  268.             parms = _quoteall(parms[0])
  269.         else:
  270.             parms = self._unicodeConvert(parms)
  271.             parms = tuple(map(_quote, parms))
  272.         self.rs = self.con.db.execute(SQL % parms)
  273.         self.closed = 0
  274.         self.current_recnum = 0
  275.         (self.rowcount, self._real_rowcount) = [
  276.             len(self.rs.row_list)] * 2
  277.         if self.rowcount == 0:
  278.             self.rowcount = self.con.db.sqlite_changes()
  279.         
  280.         self.description = self.rs.col_defs
  281.         if issubclass(self.rowclass, PgResultSet):
  282.             self.rowclass = make_PgResultSetClass(self.description[:])
  283.         
  284.  
  285.     
  286.     def executemany(self, query, parm_sequence):
  287.         self._checkNotClosed('executemany')
  288.         if self.con is None:
  289.             raise _sqlite.ProgrammingError, 'connection is closed.'
  290.         
  291.         for _i in parm_sequence:
  292.             self.execute(query, _i)
  293.         
  294.  
  295.     
  296.     def close(self):
  297.         if self.con and self.con.closed:
  298.             raise _sqlite.ProgrammingError, "This cursor's connection is already closed."
  299.         
  300.         if self.closed:
  301.             raise _sqlite.ProgrammingError, 'This cursor is already closed.'
  302.         
  303.         self.closed = 1
  304.         
  305.         try:
  306.             cursors = self.con.cursors
  307.             del cursors.data[id(self)]
  308.         except:
  309.             pass
  310.  
  311.  
  312.     
  313.     def __del__(self):
  314.         
  315.         try:
  316.             cursors = self.con.cursors
  317.             del cursors.data[id(self)]
  318.         except:
  319.             pass
  320.  
  321.  
  322.     
  323.     def setinputsizes(self, sizes):
  324.         '''Does nothing, required by DB API.'''
  325.         self._checkNotClosed('setinputsize')
  326.  
  327.     
  328.     def setoutputsize(self, size, column = None):
  329.         '''Does nothing, required by DB API.'''
  330.         self._checkNotClosed('setinputsize')
  331.  
  332.     
  333.     def fetchone(self):
  334.         self._checkNotClosed('fetchone')
  335.         if self._real_rowcount == 0:
  336.             return None
  337.         
  338.         if self.current_recnum >= self._real_rowcount:
  339.             return None
  340.         
  341.         if type(self.rowclass) is TupleType:
  342.             retval = self.rs.row_list[self.current_recnum]
  343.         else:
  344.             retval = self.rowclass(self.rs.row_list[self.current_recnum])
  345.         self.current_recnum += 1
  346.         return retval
  347.  
  348.     
  349.     def fetchmany(self, howmany = None):
  350.         self._checkNotClosed('fetchmany')
  351.         if howmany is None:
  352.             howmany = self.arraysize
  353.         
  354.         if self._real_rowcount == 0:
  355.             return []
  356.         
  357.         if self.current_recnum >= self._real_rowcount:
  358.             return []
  359.         
  360.         self.current_recnum += howmany
  361.         return retval
  362.  
  363.     
  364.     def fetchall(self):
  365.         self._checkNotClosed('fetchall')
  366.         if self._real_rowcount == 0:
  367.             return []
  368.         
  369.         if self.current_recnum >= self._real_rowcount:
  370.             return []
  371.         
  372.         self.current_recnum = self._real_rowcount
  373.         return retval
  374.  
  375.     
  376.     def __iter__(self):
  377.         return self
  378.  
  379.     
  380.     def next(self):
  381.         item = self.fetchone()
  382.         if item is None:
  383.             if sys.version_info[:2] >= (2, 2):
  384.                 raise StopIteration
  385.             else:
  386.                 raise IndexError
  387.         else:
  388.             return item
  389.  
  390.     
  391.     def scroll(self, value, mode = 'relative'):
  392.         if mode == 'relative':
  393.             new_recnum = self.current_recnum + value
  394.         elif mode == 'absolute':
  395.             new_recnum = value
  396.         else:
  397.             raise ValueError, 'invalid mode parameter'
  398.         if new_recnum >= 0 and new_recnum < self.rowcount:
  399.             self.current_recnum = new_recnum
  400.         else:
  401.             raise IndexError
  402.  
  403.     
  404.     def __getattr__(self, key):
  405.         if self.__dict__.has_key(key):
  406.             return self.__dict__[key]
  407.         elif key == 'sql':
  408.             return self.con.db.sql
  409.         elif key == 'rownumber':
  410.             return self.current_recnum
  411.         elif key == 'lastrowid':
  412.             return self.con.db.sqlite_last_insert_rowid()
  413.         elif key == 'connection':
  414.             return self.con
  415.         else:
  416.             raise AttributeError, key
  417.  
  418.  
  419.  
  420. class UnicodeConverter:
  421.     
  422.     def __init__(self, encoding):
  423.         self.encoding = encoding
  424.  
  425.     
  426.     def __call__(self, val):
  427.         return unicode(val, *self.encoding)
  428.  
  429.  
  430.  
  431. class Connection:
  432.     
  433.     def __init__(self, database = None, mode = 493, converters = { }, autocommit = 0, encoding = None, timeout = None, command_logfile = None, *arg, **kwargs):
  434.         if not database:
  435.             pass
  436.         database = kwargs.get('db')
  437.         if not encoding:
  438.             pass
  439.         encoding = kwargs.get('client_encoding')
  440.         self.db = _sqlite.connect(database, mode)
  441.         if type(encoding) not in (TupleType, ListType):
  442.             if not encoding:
  443.                 pass
  444.             self.encoding = (sys.getdefaultencoding(),)
  445.         else:
  446.             self.encoding = encoding
  447.         register = self.db.register_converter
  448.         register('str', str)
  449.         register('int', int)
  450.         register('long', long)
  451.         register('float', float)
  452.         register('unicode', UnicodeConverter(self.encoding))
  453.         register('binary', _sqlite.decode)
  454.         if have_datetime:
  455.             register('date', DateTime.DateFrom)
  456.             register('time', DateTime.TimeFrom)
  457.             register('timestamp', DateTime.DateTimeFrom)
  458.             register('interval', DateTime.DateTimeDeltaFrom)
  459.         
  460.         for typename, conv in converters.items():
  461.             register(typename, conv)
  462.         
  463.         self.autocommit = autocommit
  464.         self.closed = 0
  465.         self.inTransaction = 0
  466.         self.cursors = weakref.WeakValueDictionary()
  467.         self.rowclass = PgResultSet
  468.         if timeout is not None:
  469.             self.db.sqlite_busy_timeout(timeout)
  470.         
  471.         self.db.set_command_logfile(command_logfile)
  472.  
  473.     
  474.     def __del__(self):
  475.         if not (self.closed):
  476.             self.close()
  477.         
  478.  
  479.     
  480.     def _checkNotClosed(self, methodname):
  481.         if self.closed:
  482.             raise _sqlite.ProgrammingError, '%s failed - Connection is closed.' % methodname
  483.         
  484.  
  485.     
  486.     def __anyCursorsLeft(self):
  487.         return len(self.cursors.data.keys()) > 0
  488.  
  489.     
  490.     def __closeCursors(self, doclose = 0):
  491.         '''__closeCursors() - closes all cursors associated with this connection'''
  492.         if self._Connection__anyCursorsLeft():
  493.             cursors = map((lambda x: x()), self.cursors.data.values())
  494.             for cursor in cursors:
  495.                 
  496.                 try:
  497.                     if doclose:
  498.                         cursor.close()
  499.                     else:
  500.                         cursor._reset()
  501.                 continue
  502.                 except weakref.ReferenceError:
  503.                     continue
  504.                 
  505.  
  506.             
  507.         
  508.  
  509.     
  510.     def _begin(self):
  511.         self.db.execute('BEGIN')
  512.         self.inTransaction = 1
  513.  
  514.     
  515.     def create_function(self, name, nargs, func):
  516.         self.db.create_function(name, nargs, func)
  517.  
  518.     
  519.     def create_aggregate(self, name, nargs, agg_class):
  520.         self.db.create_aggregate(name, nargs, agg_class)
  521.  
  522.     
  523.     def commit(self):
  524.         self._checkNotClosed('commit')
  525.         if self.autocommit:
  526.             return None
  527.         
  528.         if self.inTransaction:
  529.             self.db.execute('COMMIT')
  530.             self.inTransaction = 0
  531.         
  532.  
  533.     
  534.     def rollback(self):
  535.         self._checkNotClosed('rollback')
  536.         if self.autocommit:
  537.             raise _sqlite.ProgrammingError, 'Rollback failed - autocommit is on.'
  538.         
  539.         if self.inTransaction:
  540.             self.db.execute('ROLLBACK')
  541.             self.inTransaction = 0
  542.         
  543.  
  544.     
  545.     def close(self):
  546.         self._checkNotClosed('close')
  547.         self._Connection__closeCursors(1)
  548.         if self.inTransaction:
  549.             self.rollback()
  550.         
  551.         self.db.close()
  552.         self.closed = 1
  553.  
  554.     
  555.     def cursor(self):
  556.         self._checkNotClosed('cursor')
  557.         return Cursor(self, self.rowclass)
  558.  
  559.     
  560.     def __getattr__(self, key):
  561.         if key in self.__dict__.keys():
  562.             return self.__dict__[key]
  563.         elif key in ('IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning'):
  564.             return getattr(_sqlite, key)
  565.         else:
  566.             raise AttributeError, key
  567.  
  568.  
  569.